import BaseUI from "./BaseUI";
import LoopScroll from "./LoopScroll";

//数据和渲染分离。
//itemNode渲染数据
class ItemNodeInfo {
    text_Label: cc.Label;
    icon_Sprite: cc.Sprite;
}
//itemNode节点数据
class ItemDataInfo {
    textId: number;
    iconName: string;
}


const { ccclass, property } = cc._decorator;

@ccclass
export default class Helloworld extends BaseUI {

    private loopScroll: LoopScroll = null;
    private scrollView: cc.ScrollView = null;

    public itemDataArray: ItemDataInfo[] = [];
    public itemNodeArray: ItemNodeInfo[] = [];

    onLoad() {
        this.loopScroll = cc.find('ScrollView', this.node).getComponent('LoopScroll') as LoopScroll;
        this.scrollView = cc.find('ScrollView', this.node).getComponent(cc.ScrollView);
    }

    start() {
        //一格式化数据结构
        let maxCount: number = 80;
        for (let i = 0; i < maxCount; i++) {
            let itemDataInfo: ItemDataInfo = new ItemDataInfo();
            itemDataInfo.textId = i;
            itemDataInfo.iconName = 'animal_' + i % 12;
            this.itemDataArray.push(itemDataInfo);
        }
        //二格式化节点结构
        let showCount: number = this.scrollView.content.childrenCount;
        let itemNodes: cc.Node[] = this.scrollView.content.children;
        for (let i = 0; i < showCount; i++) {
            let itemNodeInfo: ItemNodeInfo = new ItemNodeInfo();
            itemNodeInfo.text_Label = cc.find('text', itemNodes[i]).getComponent(cc.Label);
            itemNodeInfo.icon_Sprite = cc.find('icon', itemNodes[i]).getComponent(cc.Sprite);
            this.itemNodeArray.push(itemNodeInfo);
        }

        //三使用委托模式传递this并初始化content数据
        this.loopScroll.setDelegate(this);
        this.loopScroll.initContentData(maxCount);
    }

    /**
     * 更新节点展示
     * @param n_Index 节点排列Id
     * @param d_Index 数据排列Id
     */
    public refreshInterface(n_Index: number, d_Index: number): void {
        //console.log('====1>>>', n_Index, d_Index)
        let loopIndex1: number = n_Index % this.itemNodeArray.length;
        let loopIndex2: number = d_Index % this.itemDataArray.length;
        let itemNodeInfo: ItemNodeInfo = this.itemNodeArray[loopIndex1];
        let itemDataInfo: ItemDataInfo = this.itemDataArray[loopIndex2];
        //console.log('====2>>>', loopIndex1, loopIndex2)
        
        itemNodeInfo.text_Label.string = itemDataInfo.textId.toString();
        cc.resources.load(this.itemDataArray[loopIndex2].iconName, cc.SpriteFrame, (err: Error, spriteFrame: cc.SpriteFrame) => {
            if(err){ return;}
            itemNodeInfo.icon_Sprite.spriteFrame = spriteFrame;
        })  
    }

}
